﻿using System;
using System.Collections;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	
	class XmlXmlToEditReplaceWorker
	{
		//替换xReplace.
		//现在xReplace上的Rule,OnAfterChange都没有处理.
		public static void  replace(Form form, XmlToEditContext context)
		{
			XmlDocument doc = context.Doc;
			
			XmlNode itemNode = context.ItemNode;
			XmlNode parentNode = itemNode.ParentNode;
			XmlNode siblingNode = (XmlNode) itemNode.NextSibling;
			
			if (parentNode is XmlElement)
			{
				XmlElement parentElement = (XmlElement) parentNode;
				if (itemNode is XmlAttribute)
				{
					XmlAttribute attributeItem = (XmlAttribute) itemNode;
					//CID 0137 //2008.10.11 //Begin Comment
					//if (SchemaUtil.canRemoveAttr(form, parentElement, attributeItem))
					//{
					parentElement.SetAttributeNode(attributeItem);
					//}
					//CID 0137 //2008.10.11 //End
				}
				else if (itemNode is XmlElement)
				{
					XmlElement elementItem = (XmlElement) itemNode;
					//CID 0137 //2008.10.11 //Begin Comment
					//if (SchemaUtil.canRemoveChild(form, parentElement, elementItem))
					//{
					parentElement.RemoveChild(elementItem);
					//}
					//CID 0137 //2008.10.11 //End
				}
				
				ChooseFragment existChooseFragment = context.ExistChooseFragment;
				ArrayList insertXmlNodeList = existChooseFragment.XmlNodeList;
				foreach (XmlNode insertNode in insertXmlNodeList)
				{
					if (insertNode is XmlAttribute)
					{
						XmlAttribute attribute = (XmlAttribute) insertNode;
						XmlAttribute insertAttribute = doc.CreateAttribute(attribute.Name, attribute.NamespaceURI);
						insertAttribute.Value = attribute.Value;
						parentElement.SetAttributeNode(insertAttribute);
					}
					else if (insertNode is XmlElement)
					{
						//检查Element在parentElement中子节点中的位置.
						XmlElement insertElement = (XmlElement) insertNode;
						XmlNodeList childList = parentElement.ChildNodes;
						XmlElement cloneInsertElement = CloneUtil.cloneElement(form.XmlDoc, insertElement);
						if (siblingNode != null)
						{
							parentElement.InsertBefore(cloneInsertElement, siblingNode);
						}
						else
						{
							parentElement.AppendChild(cloneInsertElement);
						}
						form.NewStructureNode = cloneInsertElement;
					}
				}
			}
		}
	}
}